package top.eggcode.gateway.config;

import lombok.RequiredArgsConstructor;
import top.eggcode.component.redis.RedisUnit;
import top.eggcode.component.session.IdGenerator;
import top.eggcode.component.session.Session;
import top.eggcode.component.session.SimpleSession;
import top.eggcode.component.session.store.SessionStore;

import java.io.Serializable;
import java.util.Collection;

/**
 * Title: 集中式Session系统
 * Description: TODO
 * Date: 2021/6/10 0:02
 *
 * @author JiaQi Ding
 * @version 1.0
 */
@RequiredArgsConstructor
public class SharedSessionStore implements SessionStore {

    private static final int DEFAULT_EXPIRE_TIME = 1800000;

    private final RedisUnit buffer;

    private final IdGenerator idGenerator;

    /**
     * 数据key前缀
     */
    private final String KEY_PREFIX = "session:web:";


    @Override
    public Serializable create(Session session) {

        SimpleSession simpleSession = (SimpleSession) session;
        simpleSession.setId(idGenerator.generateId(simpleSession));
        buffer.setBean(KEY_PREFIX + session.getId(), session, session.getTimeout());
        return session.getId();
    }

    @Override
    public Session readSession(Serializable key) {
        return buffer.getBean(KEY_PREFIX + key, SimpleSession.class);
    }

    @Override
    public void update(Session session) {
        buffer.setBean(KEY_PREFIX + session.getId(), session, session.getTimeout());
    }

    @Override
    public void delete(Session session) {
        buffer.del(KEY_PREFIX + session.getId());
    }

    @Override
    public Collection<Session> getActiveSessions() {
        return null;
    }
}
